package com.bi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bi.common.ErrorCode;
import com.bi.common.ResultBean;
import com.bi.model.pojo.BTree;
import com.bi.model.pojo.Indes;
import com.bi.service.IndesService;
import com.bi.utils.CommonUtils;
import com.bi.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/btree")
public class BTeeController {

    @Autowired
    IndesService indesService;

    @Autowired
    private BTree bTree;

    /**
     * 获取某个用户创建的所有表格
     */
    @GetMapping("/list")
    public ResultBean<List<Indes>> list() {
        List<Indes> indesList = indesService.list();
        return ResultUtil.success(indesList);
    }

    @GetMapping("/getByKey/{key}")
    public ResultBean<String> getByKey(@PathVariable int key) {
        String value = bTree.find(key);
        return ResultUtil.success(value);
    }

    @PostMapping("/add")
    public ResultBean<Boolean> add(@RequestBody Indes indes) {
        Long startTime = System.currentTimeMillis();
        CommonUtils.checkNullParams(indes);
        boolean saveFlag = indesService.save(indes);
        CommonUtils.check(!saveFlag, ErrorCode.NO_FOUND_ERROR, "保存失败");
        // 添加索引
        bTree.insert(indes.getKeyy(), indes.getValue());
        Long gapTime = System.currentTimeMillis() - startTime;
        System.out.println("gapTime:" + gapTime);
        return ResultUtil.success(true);
    }

    @GetMapping("/del/{key}")
    public ResultBean<Boolean> del(@PathVariable("key") Integer key) {
        Long startTime = System.currentTimeMillis();

        CommonUtils.checkNullParams(key);
        QueryWrapper<Indes> indesQueryWrapper = new QueryWrapper<>();
        indesQueryWrapper.eq("keyy", key);
        boolean saveFlag = indesService.remove(indesQueryWrapper);
        CommonUtils.check(!saveFlag, ErrorCode.NO_FOUND_ERROR, "保存失败");
//        bTree.delete(key);
        Long gapTime = System.currentTimeMillis() - startTime;
        System.out.println("gapTime:" + gapTime);
        return ResultUtil.success(true);
    }

    @PutMapping("/edit")
    public ResultBean<Boolean> del(@RequestBody Indes indes) {
        Long startTime = System.currentTimeMillis();

        CommonUtils.checkNullParams(indes);
        UpdateWrapper<Indes> indesUpdateWrapper = new UpdateWrapper<>();
        indesUpdateWrapper.eq("keyy", indes.getKeyy());
        boolean saveFlag = indesService.update(indes, indesUpdateWrapper);
        CommonUtils.check(!saveFlag, ErrorCode.NO_FOUND_ERROR, "修改失败");

        Long gapTime = System.currentTimeMillis() - startTime;
        System.out.println("gapTime:" + gapTime);
        return ResultUtil.success(true);
    }
}
